<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.0.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/wang-cheng/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/wang-cheng/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/wang-cheng/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/wang-cheng/images/logo.svg" color="#222">

<link rel="stylesheet" href="/wang-cheng/css/main.css">


<link rel="stylesheet" href="/wang-cheng/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"cheng-wang123.gitee.io","root":"/wang-cheng/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="Spring AOP什么是AOPAOP(Aspect Orient Programming)，面向切面编程。它是面向对象编程的一种补充，主要用于处理一些具有横切性质的系统级服务，如日志收集、事务管理、安全检查、缓存、对象池管理等 AOP实现的关键在于AOP框架自动创建的AOP代理，AOP代理则可分为静态代理和动态代理，静态代理是指使用AOP框架提供的命令进行编译，从而在编译阶段就可生成AOP代理类">
<meta property="og:type" content="article">
<meta property="og:title" content="Spring学习笔记(二)">
<meta property="og:url" content="https://cheng-wang123.gitee.io/wang-cheng/2022/03/07/Spring%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E4%BA%8C/index.html">
<meta property="og:site_name" content="诚の博客">
<meta property="og:description" content="Spring AOP什么是AOPAOP(Aspect Orient Programming)，面向切面编程。它是面向对象编程的一种补充，主要用于处理一些具有横切性质的系统级服务，如日志收集、事务管理、安全检查、缓存、对象池管理等 AOP实现的关键在于AOP框架自动创建的AOP代理，AOP代理则可分为静态代理和动态代理，静态代理是指使用AOP框架提供的命令进行编译，从而在编译阶段就可生成AOP代理类">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-03-07T03:55:03.000Z">
<meta property="article:modified_time" content="2022-03-07T08:52:39.780Z">
<meta property="article:author" content="王诚">
<meta property="article:tag" content="Spring理论知识">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://cheng-wang123.gitee.io/wang-cheng/2022/03/07/Spring%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E4%BA%8C/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Spring学习笔记(二) | 诚の博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/wang-cheng/atom.xml" title="诚の博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/wang-cheng/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">诚の博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">记录学习中的点点滴滴</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/wang-cheng/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/wang-cheng/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/wang-cheng/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/wang-cheng/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://cheng-wang123.gitee.io/wang-cheng/2022/03/07/Spring%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E4%BA%8C/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/wang-cheng/images/avatar.gif">
      <meta itemprop="name" content="王诚">
      <meta itemprop="description" content="命运对勇士低语，你无法抵御风暴；勇士低声回应，我就是风暴">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="诚の博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Spring学习笔记(二)
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2022-03-07 11:55:03 / 修改时间：16:52:39" itemprop="dateCreated datePublished" datetime="2022-03-07T11:55:03+08:00">2022-03-07</time>
            </span>

          
            <span class="post-meta-item" title="阅读次数" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">阅读次数：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="Spring-AOP"><a href="#Spring-AOP" class="headerlink" title="Spring AOP"></a><strong>Spring AOP</strong></h1><h2 id="什么是AOP"><a href="#什么是AOP" class="headerlink" title="什么是AOP"></a><strong>什么是AOP</strong></h2><p><code>AOP(Aspect Orient Programming)</code>，面向切面编程。它是面向对象编程的一种补充，主要用于处理一些具有横切性质的系统级服务，如<strong>日志收集、事务管理、安全检查、缓存、对象池管理</strong>等</p>
<p><code>AOP</code>实现的关键在于<code>AOP</code>框架自动创建的<code>AOP</code>代理，<code>AOP</code>代理则可分为静态代理和动态代理，静态代理是指使用<code>AOP</code>框架提供的命令进行编译，从而在编译阶段就可生成<code>AOP</code>代理类，因此也被成为编译时增强；而动态代理则在运行时借助于JDK动态代理、CGLib动态代理等在内存中”临时“生成<code>AOP</code>动态代理类，因此也被称为运行时增强。</p>
<p><code>AOP</code>要实现的是在我们写的代码的基础上进行一定的封装，如在方法执行前、或执行后、或执行中出现异常后这些地方进行拦截处理或叫做增强处理。</p>
<h2 id="动态代理"><a href="#动态代理" class="headerlink" title="动态代理"></a><strong>动态代理</strong></h2><ol>
<li>JDK动态代理：使用JDK的<code>Proxy</code>,<code>Method</code>,<code>InvocationHandler</code>创建代理对象，JDK动态代理要求目标类必须实现接口</li>
<li>CGLib动态代理：第三方的工具库，底层使用的是字节码技术。创建代理对象，原理是继承。通过继承目标类，创建子类，子类就是代理类，要求目标类或方法不能是final</li>
</ol>
<h2 id="动态代理的作用"><a href="#动态代理的作用" class="headerlink" title="动态代理的作用"></a><strong>动态代理的作用</strong></h2><ol>
<li>在目标类源代码不改变的基础上，增加功能。</li>
<li>减少代码的重复</li>
<li>专注业务逻辑</li>
<li>解耦合，让你的业务功能和日志、事务非业务功能分离</li>
</ol>
<h2 id="Sprng-AOP"><a href="#Sprng-AOP" class="headerlink" title="Sprng AOP"></a><strong>Sprng AOP</strong></h2><p><code>Spring AOP</code>底层是动态代理实现的，采用了JDK和CGLib两种代理方式。</p>
<h3 id="Spring-AOP代理创建的过程"><a href="#Spring-AOP代理创建的过程" class="headerlink" title="Spring AOP代理创建的过程"></a><strong>Spring AOP代理创建的过程</strong></h3><ol>
<li><p>在上一节中讲到了扫描到所有的Bean后将Bean封装成一个个的BeanDifinition，然后存入BeanDifinitionMap中，然后在从中取出依次进行实例化。在实例化之前会有一个拦截，<code>InstantiationAwareBeanPostProcessor</code>，会调用该接口的<code>postProcessBeforeInstantiation()</code>方法。</p>
</li>
<li><p>这个方法会在内部进行一系列的判断，判断当前Bean是否在advisedBeans中（保存了所有需要增强的bean）、判断当前bean是否是基础类型的<code>Advice</code>、<code>Pointcut</code>、<code>Advisor</code>、<code>AopInfrastructureBean</code>、判断是否是切面（是否实现了注解<code>@Aspect</code>）、判断是否需要跳过等(符合条件的Bean都是我们自己实现的切面类)。在判断过程中会拿到增强Bean的相关通知方法，并通过这些切面进行逻辑判断</p>
</li>
<li><p>执行完<code>postProcessBeforeInstantiation()</code>方法后执行<code>postProcessAfterInitialization</code>方法。<br>该方法会对切面进行依次包装处理，在包装过程中创建了一个代理对象(此时要代理的对象，是我们需要增强的类或方法，一般是@Service层或Controller层)</p>
</li>
<li><p>细看创建代理对象的过程，会发现在创建之前首先会遍历容器中所有的Bean，并找出声明<code>AspectJ</code>注解的类，近标记的类进行增强器的提取，最终拿到所有的增强器<code>advisor</code>(增强器中定义了切点Pointcut，通知父类Advice)并放入缓存。</p>
</li>
<li><p>创建一个代理工厂，将所有的增强器和目标类(需要增强的类)注入代理工厂，再用代理工厂创建对象。</p>
</li>
<li><p>代理工厂会选择<code>JdkDynamicAopProxy</code>或者<code>CglibAopProxy</code>，主要通过是否是接口和是否配置了<code>cglib</code>代理决定的。最终工厂会创建一个代理增强的对象。(这个增强的对象不是所谓动态代理中通过代理得到的代理类，该增强的对象里面只是保存了比如增强器、目标对象等信息，方便后面拦截器去真正的执行你所编写的AOP的功能)最终代理工厂会将创建的所有代理增强的对象全部添加到容器。以后容器中获取到的就是这个组件的代理对象。</p>
</li>
<li><p>当我们执行目标方法时，<code>CglibAopProxy.intercept()</code>会拦截目标方法的执行，根据<code>ProxyFactory</code>对象获取将要执行的目标方法拦截器链,之后，会将拦截器链和目标对象等传入methodInvocation，并调用proceed()方法。该方法执行也是拦截器的触发过程，也是目标方法的主要执行过程。通过索引遍历拦截器链中的所有的拦截器（封装的增强器），并分别执行增强方法。每次执行拦截器方法索引自增，直至所有的增强方法执行完毕。</p>
</li>
</ol>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/wang-cheng/tags/Spring%E7%90%86%E8%AE%BA%E7%9F%A5%E8%AF%86/" rel="tag"># Spring理论知识</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/wang-cheng/2022/03/06/Spring%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E4%B8%80/" rel="prev" title="Spring学习笔记(一)">
      <i class="fa fa-chevron-left"></i> Spring学习笔记(一)
    </a></div>
      <div class="post-nav-item">
    <a href="/wang-cheng/2022/03/07/Spring%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-%E4%B8%89/" rel="next" title="Spring学习笔记(三)">
      Spring学习笔记(三) <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Spring-AOP"><span class="nav-number">1.</span> <span class="nav-text">Spring AOP</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E6%98%AFAOP"><span class="nav-number">1.1.</span> <span class="nav-text">什么是AOP</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86"><span class="nav-number">1.2.</span> <span class="nav-text">动态代理</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8A%A8%E6%80%81%E4%BB%A3%E7%90%86%E7%9A%84%E4%BD%9C%E7%94%A8"><span class="nav-number">1.3.</span> <span class="nav-text">动态代理的作用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Sprng-AOP"><span class="nav-number">1.4.</span> <span class="nav-text">Sprng AOP</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Spring-AOP%E4%BB%A3%E7%90%86%E5%88%9B%E5%BB%BA%E7%9A%84%E8%BF%87%E7%A8%8B"><span class="nav-number">1.4.1.</span> <span class="nav-text">Spring AOP代理创建的过程</span></a></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">王诚</p>
  <div class="site-description" itemprop="description">命运对勇士低语，你无法抵御风暴；勇士低声回应，我就是风暴</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/wang-cheng/archives/">
        
          <span class="site-state-item-count">32</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/wang-cheng/tags/">
          
        <span class="site-state-item-count">12</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">王诚</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/wang-cheng/lib/anime.min.js"></script>
  <script src="/wang-cheng/lib/velocity/velocity.min.js"></script>
  <script src="/wang-cheng/lib/velocity/velocity.ui.min.js"></script>

<script src="/wang-cheng/js/utils.js"></script>

<script src="/wang-cheng/js/motion.js"></script>


<script src="/wang-cheng/js/schemes/pisces.js"></script>


<script src="/wang-cheng/js/next-boot.js"></script>




  















  

  

  

</body>
</html>
